import { client } from '../../request/index.js'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'

// var uid = wx.getStorageSync('userId')
Page({
  data: {
    screenWidth: 0,
    screenHeight: 0,
    isLogin: false,
    ip: getApp().globalData.ip,
    imgIp: getApp().globalData.imgIp,
    swiperArray: [],
    rank_e: '0',
    rank_l: '0',
    badges: [],
    flexWidth: 0,
    flexHeight: 0,
    showModal: false,
    rewardNumber: null,
    invitaterId: '', // 从分享链接进入所获得的分享者userid
    guide1: false, // 显示登录引导1
    guideBox: 2, // 显示引导按钮（有2个按钮）
    guideYellow: true,
    guideRed: true,
    guide2: false, // 显示打卡引导2
    guide4: false, // 显示打卡成功引导4
  },
  // 用户登录页面设置全局userId
  async setUserId() {
    const mapData = await client({
      url: '/account/detail',
    })
    getApp().globalData.userId = mapData.data.data.userId
    this.setData({
      isLogin: true,
    })
    this.getEmpty()
    this.getLove()
    this.getHonor()
  },
  // 登录
  login() {
    let that = this
    wx.getUserInfo({
      success(u) {
        getApp().globalData.nickName = u.userInfo.nickName
        getApp().globalData.avatarUrl = u.userInfo.avatarUrl
        wx.login({
          success(res) {
            if (res.code) {
              wx.request({
                url: getApp().globalData.ip + '/login',
                data: {
                  code: res.code,
                  username: getApp().globalData.nickName,
                  headImg: getApp().globalData.avatarUrl,
                  invitaterId: getApp().globalData.invitaterId,
                },
                method: 'POST',
                header: {
                  'content-type': 'application/json;charset=utf-8',
                },
                dataType: 'json',
                success: (res1) => {
                  wx.setStorageSync('sessionid', res1.data.data.session)
                  getApp().globalData.sessionid = res1.data.data.session
                  getApp().globalData.roleName = res1.data.data.roleName
                  getApp().globalData.userType = res1.data.data.description
                  if (res1.statusCode == '200') {
                    console.log('登录成功！')
                    that.setUserId()
                  } else {
                    //无网络
                    Dialog.alert({
                      title: '提示',
                      message: '请检查您的网络',
                    })
                  }
                },
                fail() {
                  console.log('发起登录请求失败！')
                },
              })
            } else {
              console.log('登录失败！' + res.errMsg)
            }
          },
        })
      },
    })
  },
  // 跳转个人登录
  toLogin() {
    getApp().globalData.showLoginDialog = true
    Dialog.alert({
      title: '前往登录',
      message: '将为您跳转到其它界面进行登录',
    }).then(() => {
      wx.switchTab({
        url: '../../pages/my/my',
      })
    })
  },
  // 跳转打卡
  toPhoto() {
    if (getApp().globalData.sessionid === '') {
      getApp().globalData.showLoginDialog = true
      Dialog.alert({
        title: '检测到尚未登录',
        message: '将为您跳转到其它界面进行登录',
      }).then(() => {
        wx.switchTab({
          url: '../../pages/my/my',
        })
      })
    } else {
      wx.navigateTo({
        url: '/pages/photo_h/photo_h',
      })
    }
  },
  // 渲染轮播图片
  async getImgUrl() {
    const res = await client({
      url: '/article/picture',
    })
    console.log('轮播图信息:', res)
    let swiperArray = res.data.data
    this.setData({
      swiperArray,
    })
  },
  // 取消成功窗
  cancelDialog() {
    if (this.data.guide4 === true) {
      wx.setStorage({
        key: 'successGuideOpen',
        data: false,
      })
    }
    this.setData({
      showModal: false,
      guide4: false,
    })
    let changeToGuideBox = wx.getStorageSync('changeToGuideBox')
    if (changeToGuideBox === true) {
      this.setData({
        guideBox: true,
      })
    }
  },
  // 跳转徽章
  toHonor() {
    wx.navigateTo({
      url: '/pages/honor/honor',
    })
  },
  // 跳转公众号文章
  swiperClick(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/swiper/swiper?swiperId=' + id,
    })
  },
  // 跳转助力排行榜
  todt() {
    wx.navigateTo({
      url: '/pages/dt_rank/dt_rank',
    })
  },
  // 跳转打卡排行榜
  toClock() {
    wx.navigateTo({
      url: '/pages/clock_rank/clock_rank',
    })
  },
  // 返回排行1
  async getEmpty() {
    let uid = getApp().globalData.userId
    const r = await client({
      url: `${'/ranking/clock'}/${uid}`,
    })
    console.log('光盘排名:', r)
    this.setData({
      rank_e: r.data.id,
    })
  },
  // 返回排行2
  async getLove() {
    let uid = getApp().globalData.userId
    const r = await client({
      url: `${'/ranking/donate'}/${uid}`,
    })
    console.log('助力排名:', r)
    this.setData({
      rank_l: r.data.id,
    })
  },
  // 返回徽章
  async getHonor() {
    let that = this
    let uid = wx.getStorageSync('userId')
    const h = await client({
      url: '/badge/userbadge',
      data: {
        userId: uid,
      },
    })
    console.log('徽章:', h)
    if (h.data.data === undefined) {
      return
    }
    let badges = []
    let item1 = {}
    let item2 = {}
    if (h.data.data.ClockBadgeName !== undefined) {
      item1.name = h.data.data.ClockBadgeName
      badges.push(item1)
    }
    if (h.data.data.DonateBadgeName !== undefined) {
      item2.name = h.data.data.DonateBadgeName
      badges.push(item2)
    }
    that.setData({
      badges,
    })
  },
  // 跳转用户手册
  help() {
    wx.navigateTo({
      url: '/pages/help/help',
    })
  },
  // 跳转tabbar
  switchDo() {
    wx.switchTab({
      url: '../dt/dt',
    })
  },
  // 引导1知道了
  guide1_cancel() {
    wx.setStorage({
      key: 'loadOpen',
      data: 'known',
    })
    this.setData({
      guide1: false,
    })
  },
  // 引导2知道了
  guide2_cancel() {
    let guideOpen = wx.getStorageSync('guideOpen')
    // 有一个按钮没点就还要显示guideBox
    this.setData({
      guide2: false,
      guideBox: guideOpen,
    })
    wx.setStorage({
      key: 'clockGuideOpen',
      data: false,
    })
    wx.setStorage({
      key: 'photoGuideOpen',
      data: true,
    })
    wx.navigateTo({
      url: '../photo_h/photo_h',
    })
  },
  //引导2跳过
  guide2_skip() {
    this.setData({
      guide2: false,
    })
  },
  // 选择光盘引导
  toGuideClock() {
    // 判断是不是两个按钮都点过了，点过就不显示按钮引导了
    let guideOpen = wx.getStorageSync('guideOpen') - 1
    wx.setStorage({
      key: 'guideOpen',
      data: guideOpen,
    })
    wx.setStorage({
      key: 'clockGuideOpen',
      data: true,
    })
    this.setData({
      guideYellow: false,
      guide2: true,
      guideBox: 0,
    })
  },
  // 选择助力引导
  toGuideDt() {
    // 判断是不是两个按钮都点过了，点过就不显示按钮引导了
    let guideOpen = wx.getStorageSync('guideOpen') - 1
    wx.setStorage({
      key: 'guideOpen',
      data: guideOpen,
    })
    this.setData({
      guideRed: false,
      guideBox: 0,
    })
    wx.setStorage({
      key: 'dtGuideOpen',
      data: 'unknown',
    })
    wx.switchTab({
      url: '../dt/dt',
    })
  },
  //双引导跳过
  guide3_skip() {
    this.setData({
      guideBox: 0,
    })
    wx.setStorage({
      data: 0,
      key: 'guideOpen',
    })
  },

  onLoad(options) {
    let that = this
    //查看是否授权
    that.getImgUrl()
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          console.log('已经授过权，直接登录')
          that.login()
        }
      },
    })
    if (options.invitaterId) {
      getApp().globalData.invitaterId = options.invitaterId
    }
    // 判断是否第一次打开小程序
    let loadOpen = wx.getStorageSync('loadOpen')
    if (loadOpen == undefined || loadOpen == '') {
      this.setData({
        guide1: true,
      })
    } else {
      this.setData({
        guide1: false,
      })
    }
    //设备信息
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          screenHeight: res.windowHeight,
          screenWidth: res.windowWidth,
        })
      },
    })
  },

  onShow() {
    // 登录了
    if (getApp().globalData.sessionid !== '') {
      this.setData({
        isLogin: true,
      })
      this.getEmpty()
      this.getLove()
      this.getHonor()
    }
    // 判断是否显示过双按钮引导
    let guideOpen = wx.getStorageSync('guideOpen')
    let clockGuideOpen = wx.getStorageSync('clockGuideOpen')
    if (guideOpen > 0 && clockGuideOpen !== true) {
      this.setData({
        guideBox: true,
      })
    } else {
      this.setData({
        guideBox: false,
      })
    }
    // 打卡成功（一定要放最后，不然第一次打卡成功返回首页时guideBox还为true还会显示按钮）
    if (getApp().globalData.rewardNumber !== 2) {
      this.setData({
        rewardNumber: getApp().globalData.rewardNumber,
        showModal: true,
      })
      getApp().globalData.rewardNumber = 2
      // 是否第一次打卡成功
      let successGuideOpen = wx.getStorageSync('successGuideOpen')
      if (successGuideOpen === true) {
        let guideOpen = wx.getStorageSync('guideOpen')
        // 成功跳转时首页还存在之前的双按钮引导，要关闭之前的引导
        if (guideOpen > 0) {
          this.setData({
            guide4: true,
            guideBox: false,
          })
          wx.setStorage({
            key: 'changeToGuideBox',
            data: true,
          })
        } else {
          this.setData({
            guide4: true,
          })
        }
      }
    }
  },

  onReady() {
    let that = this
    setTimeout(() => {
      let timer = setInterval(() => {
        that.setData({
          flexWidth: that.data.flexWidth + 5,
          flexHeight: that.data.flexHeight + 4.25,
        })
        if (that.data.flexWidth > that.data.screenWidth * 0.7) {
          clearInterval(timer)
        }
      }, 10)
    }, 2000)
  },
  onShareAppMessage(res) {
    var vm = this
    if (res.from === 'button') {
      console.log('onShareAppMessage()==>>来自页面内转发按钮')
      console.log(res.target)
    } else {
      console.log('onShareAppMessage()==>>来自右上角转发菜单')
    }
    return {
      title: '让光盘成为习惯，让爱心不断传递！',
      path: 'pages/homepage/homepage',
      imageUrl: '../../images/share.png',
      success: function (res) {
        console.log('分享success()')
        console.log('onShareAppMessage()==>>转发成功', res)
        //分享的是群还是个人
        getApp().setInfo(res)
      },
      fail: (res) => {
        console.log('onShareAppMessage()==>>转发失败', res)
      },
    }
  },
})
